package org.star.dolphin.utils;

import org.apache.commons.lang3.StringUtils;

import java.io.File;
import java.io.IOException;
import java.util.*;

public class MarkdownUtil {

    private static String DESIGN_PATH = "db/design/";

    private static String SQL_PATH = "db/sql/";

    private static Map<String, String> IS_NULL = new HashMap<String, String>() {{
        put("是", "DEFAULT NULL");
        put("否", "NOT NULL");
    }};

    private static Map<String, String> INDEX = new HashMap<String, String>() {{
        put("Normal", "INDEX");
    }};

    /**
     * markdown转SQL脚本
     *
     * @param fileName
     * @param contentList
     * @throws IOException
     */
    public static void markdown2Sql(String fileName, List<String> contentList) throws IOException {
        final String TABLE_NAME = "`" + fileName + "`";
        final String CHANGE_LINE = "\r\n";
        StringBuilder builderSql = new StringBuilder();
        builderSql.append("DROP TABLE IF EXISTS ").append(TABLE_NAME).append(";").append(CHANGE_LINE);
        builderSql.append("CREATE TABLE ").append(TABLE_NAME).append(" (").append(CHANGE_LINE);
        String primaryKey = "";
        List<String> fields = new ArrayList<>();
        List<String> indexes = new ArrayList<>();
        Boolean field = false;
        Boolean index = false;

        //剔除信息
        Iterator<String> iterator = contentList.iterator();
        while (iterator.hasNext()) {
            String rowContent = iterator.next();

            if (StringUtils.isBlank(rowContent) && index) {
                index = false;
            }

            if (StringUtils.isBlank(rowContent) && field) {
                field = false;
            }

            if (field) {
                fields.add(rowContent);
            }
            if (index) {
                indexes.add(rowContent);
            }

            if (rowContent.length() >= 6 && StringUtils.equalsAnyIgnoreCase("## 字段：", rowContent.substring(0, 6))) {
                field = true;
            }


            if (rowContent.length() >= 6 && StringUtils.equalsAnyIgnoreCase("## 索引：", rowContent.substring(0, 6))) {
                index = true;
            }

            if (rowContent.length() >= 6 && StringUtils.equalsAnyIgnoreCase("## 主键：", rowContent.substring(0, 6))) {
                List<String> rowContents = Arrays.asList(rowContent.split("：", -1));
                primaryKey = rowContents.get(1).trim();
            }
        }

        //生成脚本
        for (String item : fields) {
            List<String> rowContents = new ArrayList<>(Arrays.asList(item.split("\\|", -1)));

            //移除表格第一,二行
            if (StringUtils.equalsAnyIgnoreCase(rowContents.get(1).trim(), "字段名")) {
                continue;
            }
            if (StringUtils.equalsAnyIgnoreCase(rowContents.get(1).trim(), ":---:")) {
                continue;
            }

            //field
            builderSql.append("`").append(rowContents.get(1).trim()).append("` ").append(rowContents.get(2).trim()).append(" ")
                    .append(IS_NULL.get(rowContents.get(3).trim())).append(" ").append(rowContents.get(4).trim()).append(" COMMENT ")
                    .append("'").append(rowContents.get(5).trim()).append("'").append(",").append(CHANGE_LINE);

        }

        builderSql.append("PRIMARY KEY (").append(primaryKey).append(")");
        builderSql.append(") ENGINE=InnoDB DEFAULT CHARSET=utf8;");
        builderSql.append(CHANGE_LINE);

        for (String item : indexes) {
            List<String> rowContents = new ArrayList<>(Arrays.asList(item.split("\\|", -1)));

            //移除表格第一,二行
            if (StringUtils.equalsAnyIgnoreCase(rowContents.get(1).trim(), "索引名")) {
                continue;
            }
            if (StringUtils.equalsAnyIgnoreCase(rowContents.get(1).trim(), ":---:")) {
                continue;
            }

            builderSql.append("ALTER TABLE ")
                    .append(fileName)
                    .append(" ADD ")
                    .append(INDEX.get(rowContents.get(2).trim()))
                    .append(" ").append(rowContents.get(1).trim()).append(" ")
                    .append("(").append(rowContents.get(3).trim()).append(");");
            builderSql.append(CHANGE_LINE);
        }

        //写入文件
        FileUtil.writeAll(SQL_PATH + fileName + ".sql", builderSql.toString());
    }

    /**
     * markdown转domain
     *
     * @param markdownContent
     */
    public static void markdown2Domain(String markdownContent) {

    }

/*    *//**
     * Run
     *
     * @param args
     *//*
    public static void main(String[] args) {
        try {
            //读取所有文件
            File dir = new File(DESIGN_PATH);
            String[] names = dir.list();

            for (String name : names) {
                String fileName = name.split("\\.", -1)[0];
                String content = FileUtil.readAll(DESIGN_PATH + name);
                List<String> contentList = new ArrayList<>(Arrays.asList(content.split("\r\n", -1)));
                System.out.println("----------------------->create sql " + name + " start...");
                //生成SQL脚本
                markdown2Sql(fileName, contentList);
                System.out.println("----------------------->create sql " + name + " end...");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }*/

}
